package com.gonsin.ta.logic.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class ValueUtils {

    private static List<String> BASE_TYPE = Arrays.asList(
            "int", "byte", "boolean", "double", "float", "short", "char", "long",
            String.class.getName(),
            Integer.class.getName(),
            Byte.class.getName(),
            Boolean.class.getName(),
            Double.class.getName(),
            Float.class.getName(),
            Short.class.getName(),
            Character.class.getName(),
            Long.class.getName()
    );

    /**
     * 判断是否是基础数据类型的包装类型
     */
    public static boolean isWrapClass(Class clz) {
        try {
            if(BASE_TYPE.contains(clz.getName())){
                return true;
            }
            return ((Class) clz.getField("TYPE").get(null)).isPrimitive();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * TODO 将字符串转化成任意类型
     */
    public static <T> T parseValue(Object obj, Type type) {
        if(obj == null){
            return null;
        }
        String value = (obj instanceof String) ? (String) obj : obj.toString();
        if(value == null){
            return null;
        }
        if(type.equals(String.class)){
            return (T) value;
        }
        if(value.equals("")){
            return null;
        }
        if(Integer.class == type){
            return (T) Integer.class.cast(Double.valueOf(value).intValue());
        }
        if(Long.class == type){
            return (T) Long.class.cast(Double.valueOf(value).longValue());
        }
        if(String.class == type){
            return (T) value;
        }
        if(Boolean.class == type){
            return (T) (Boolean.valueOf("true".equalsIgnoreCase(value)));
        }
        if(Float.class == type){
            return (T)Float.valueOf(value);
        }
        if(Double.class == type){
            return (T)Double.valueOf(value);
        }
        if(Byte.class == type){
            return (T) Byte.class.cast(Float.valueOf(value).byteValue());
        }
        if(Short.class == type){
            return (T) Short.class.cast(Float.valueOf(value).shortValue());
        }
        if(Character.class == type){
            return (T)Character.valueOf(value.toCharArray()[0]);
        }
        Gson gson = new GsonBuilder()
                .enableComplexMapKeySerialization()
                .disableHtmlEscaping().create();
        Object map = gson.fromJson(value, type);
        return (T) map;
    }
}
